import axios from 'axios'
import type { Document, DocumentItem, DocumentItemRequest, DocumentFavorite, DocumentFavoriteRequest } from '../types/document'
import type { NameSpace, CreateNameSpaceRequest, UpdateNameSpaceRequest } from '../types/namespace'
import type { FileUploadResponse } from '../types/file'

const api = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

export const documentApi = {
  // 根据命名空间获取文档
  getByNamespace: (namespaceId: number): Promise<Document[]> => {
    return api.get('/document/list', {
      params: { namespaceId }
    }).then(response => {
      return flattenDocumentTree(response.data.data || [])
    })
  },

  // 根据ID获取文档详情
  getById: (id: number): Promise<Document> => {
    return api.get(`/document/${id}`).then(response => {
      // 后端返回被Result包装的数据
      return response.data.data
    })
  },

  // 创建新文档
  create: (document: Omit<Document, 'id' | 'createdTime' | 'updatedTime' | 'children'>): Promise<Document> => {
    return api.post('/document', {
      name: document.name,
      content: document.content || '',
      parentId: document.parentId,
      sortNo: document.sortNo || 0
    }).then(response => {
      // 后端返回被Result包装的数据
      return response.data.data
    })
  },

  // 更新文档
  update: (id: number, document: Omit<Document, 'id' | 'createdTime' | 'updatedTime' | 'children'>): Promise<Document> => {
    return api.put(`/document/${id}`, {
      name: document.name,
      content: document.content || '',
      parentId: document.parentId,
      sortNo: document.sortNo || 0,
      namespaceId: document.namespaceId
    }).then(response => {
      // 后端返回被Result包装的数据
      return response.data.data
    })
  },

  // 删除文档
  delete: (id: number): Promise<boolean> => {
    return api.delete(`/document/${id}`).then(response => {
      // 后端返回被Result包装的数据
      return response.data.data
    })
  },

  // 搜索功能 - 暂时移除，后端还没有实现
  // searchByName: (name: string): Promise<Document[]> => {
  //   return api.get('/document/search/name', { params: { name } }).then(response => response.data)
  // },

  // searchByContent: (content: string): Promise<Document[]> => {
  //   return api.post('/document/search/content', { keyword: content }).then(response => response.data)
  // },


  // 移动文档到新的父文档下
  moveDocument: (documentId: number, newParentId: number | null, newSortNo?: number): Promise<boolean> => {
    return api.put(`/document/${documentId}/move`, {
      parentId: newParentId,
      sortNo: newSortNo || 0
    }).then(response => {
      return response.data.data
    })
  },

  // 批量更新文档排序
  updateSort: (updates: Array<{ id: number; sortNo: number }>): Promise<boolean> => {
    return api.post('/document/batch/sort', { updates }).then(response => {
      return response.data.data
    })
  }
}

export const documentItemApi = {
  // 根据文档ID获取所有子项
  getByDocumentId: (documentId: number): Promise<DocumentItem[]> => {
    return api.get(`/document-item/document/${documentId}`).then(response => {
      return response.data.data || []
    })
  },

  // 根据ID获取子项详情
  getById: (id: number): Promise<DocumentItem> => {
    return api.get(`/document-item/${id}`).then(response => {
      return response.data.data
    })
  },

  // 创建文档子项
  create: (request: DocumentItemRequest): Promise<DocumentItem> => {
    return api.post('/document-item', request).then(response => {
      return response.data.data
    })
  },

  // 更新文档子项
  update: (id: number, request: DocumentItemRequest): Promise<DocumentItem> => {
    return api.put(`/document-item/${id}`, request).then(response => {
      return response.data.data
    })
  },

  // 删除文档子项
  delete: (id: number): Promise<boolean> => {
    return api.delete(`/document-item/${id}`).then(response => {
      return response.data.data
    })
  }
}

// 将树形结构扁平化为列表
function flattenDocumentTree(treeData: any[]): Document[] {
  const result: Document[] = []
  
  function traverse(nodes: any[], parentId: number | null = null) {
    if (!Array.isArray(nodes)) return
    
    nodes.forEach(node => {
      // 获取详细信息 - DocumentListVo包含id、name、sortNo和children
      const document: Document = {
        id: node.id,
        name: node.name,
        content: '', // 需要单独获取详情
        parentId: parentId,
        sortNo: node.sortNo,
        children: node.children || []
      }
      
      result.push(document)
      
      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        traverse(node.children, node.id)
      }
    })
  }
  
  traverse(treeData)
  return result
}

export const namespaceApi = {
  // 获取所有命名空间
  getAll: (): Promise<NameSpace[]> => {
    return api.get('/namespace/list').then(response => {
      return response.data.data || []
    })
  },

  // 根据ID获取命名空间
  getById: (id: number): Promise<NameSpace> => {
    return api.get(`/namespace/${id}`).then(response => {
      return response.data.data
    })
  },

  // 创建命名空间
  create: (request: CreateNameSpaceRequest): Promise<NameSpace> => {
    return api.post('/namespace', request).then(response => {
      return response.data.data
    })
  },

  // 更新命名空间
  update: (id: number, request: UpdateNameSpaceRequest): Promise<NameSpace> => {
    return api.put(`/namespace/${id}`, request).then(response => {
      return response.data.data
    })
  },

  // 删除命名空间
  delete: (id: number): Promise<boolean> => {
    return api.delete(`/namespace/${id}`).then(response => {
      return response.data.data
    })
  }
}

export const documentFavoriteApi = {
  // 添加收藏
  addFavorite: (request: DocumentFavoriteRequest): Promise<DocumentFavorite> => {
    return api.post('/document/favorite', request).then(response => {
      return response.data.data
    })
  },

  // 取消收藏
  removeFavorite: (documentId: number): Promise<void> => {
    return api.delete(`/document/favorite/${documentId}`).then(() => {
      // 返回void
    })
  },

  // 获取收藏列表
  getAllFavorites: (): Promise<DocumentFavorite[]> => {
    return api.get('/document/favorite').then(response => {
      return response.data.data || []
    })
  },

  // 检查文档是否已收藏
  isFavorited: (documentId: number): Promise<boolean> => {
    return api.get(`/document/favorite/check/${documentId}`).then(response => {
      return response.data.data
    })
  }
}

export const fileApi = {
  // 上传图片
  uploadImage: (file: File): Promise<FileUploadResponse> => {
    const formData = new FormData()
    formData.append('file', file)
    
    return api.post('/file/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      // 上传文件超时时间设为30秒
      timeout: 30000
    }).then(response => {
      return response.data.data
    })
  }
}

export default api